import { defineStore } from "pinia";
import request from '@/utils/request'
import { ref } from 'vue'
import { ElMessage } from "element-plus";
import router from "@/router";
import { setRouter } from "@/router";
import { useUserStore } from '@/stores'
export const useLoginStore = defineStore('loginStore', () => {
    // 数据
    const userInfo = ref({})
    const userFromRef = ref({})
    const validatePass2 = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入密码'))
        } else if (value !== userInfo.value.password) {
            callback(new Error("两次输入不一致"))
        } else {
            console.log(value, userInfo.value.password)
            callback()
        }
    }
    const rules = ref({
        username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 8, message: '用户名长度在3-8', trigger: 'blur' },
        ],
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 1, max: 20, message: '密码长度在1-20', trigger: 'blur' },
        ],
        nickname: [
            { required: true, message: '请输入昵称', trigger: 'blur' },
            { min: 2, max: 6, message: '昵称长度在2-6', trigger: 'blur' },
        ],
        confirmPassword: [
            { validator: validatePass2, trigger: 'blur' },
        ]
    })

    // 方法
    const login = async () => {
        const { code, msg, data } = await request.post('/user/login', userInfo.value)
        if (code === 200) {
            // 存储用户信息到浏览器
            localStorage.setItem('userInfo', JSON.stringify(data))
            await useUserStore().getVueMenu(data.role)
            ElMessage.success('登录成功')
            
            // 登录成功之后添加路由  并跳转
            setRouter()
            router.push('/')

            // 清除输入内容
            userFromRef.value = {}
            userInfo.value = {}
        } else {
            ElMessage.warning(`${code}` + `${msg}`)
        }
    }

    const register = async () => {
        // 添加权限
        userInfo.value.role = 'ROLE_NORMAL'
        const { code, msg } = await request.post('/user/register', userInfo.value)
        if (code === 200) {
            // 存储用户信息到浏览器
            ElMessage.success('注册成功')
            router.push('/login')
            // 清除输入内容
            userFromRef.value = {}
            userInfo.value = {}
        } else {
            ElMessage.warning(`${code}` + `${msg}`)
        }
    }

    // 表单验证
    const submitForm = async (formEl, status) => {
        if (!formEl) return
        await formEl.validate((valid, fields) => {
            if (valid) {
                status ? login() : register()
            } else {
                ElMessage.error('请输入正确格式')
                console.log('校验失败', fields)
            }
        })
    }

    // const getRoleName = async (flag) => {
    //     const result = await request.get('/role/flag', {
    //         params: {
    //             flag
    //         }
    //     })
    // }

    // 登录成功之后，动态添加路由
    // const addRoute = () => {
    //     // 获取localStorage 里的userRouters
    //     const userRouters = localStorage.getItem('userRouter') ? JSON.parse(localStorage.getItem('userRouter')) : null
    //     // 定义temp 存储不在数据库中的router
    //     const childrenRouter = [{ path: 'person', component: () => import('@/views/PersonCom.vue'), meta: { isAuth: true, title: '个人信息' } }]
    //     // 处理之后存入 temp 中
    //     userRouters?.forEach(item => childrenRouter.push({ path: item.path.substring(1).split('/')[0], component: () => import(`@/views/${item.vuePage}.vue`), meta: { isAuth: true, title: item.name } }))
    //     // 添加路由
    //     childrenRouter.forEach(item => router.children.addRoute(item))
    // }

    return {
        userInfo,
        rules,
        userFromRef,
        login,
        submitForm

    }
})